package com.smarty.net.socket;

import com.smarty.net.layout.Transfer;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;

@Slf4j
public class DirectorSocket extends UpStreamSocket {
    Boolean inForwardData=false;

    public <T extends Transfer>DirectorSocket(Socket selfSocket, T remoteTransfer) throws IOException {
        super(selfSocket,remoteTransfer);
        selfSocket.setSoTimeout(50);
    }
    public void start() throws IOException {
        getSelfSocket().setSoTimeout(10000);
        inForwardData=true;
        Thread thread = new Thread(() -> {
            try {
                remote2Self();
            } catch (Exception e) {
                inForwardData = false;
                throw new RuntimeException(e);
            }
        });
        Thread thread2 = new Thread(() -> {
            try {
                self2Remote();
            } catch (Exception e) {
                inForwardData = false;
                throw new RuntimeException(e);
            }
        });

        thread.start();
        thread2.start();
        try{
            thread2.join(5000);
            if(thread2.isAlive()){
                thread2.interrupt();
            }
            if(thread.isAlive()){
                thread.interrupt();
            }
        }catch (InterruptedException e){

        }
        log.info("Director线程结束");
    }
}
